package io.github.iogogogo.scheduled.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Maps;
import io.github.iogogogo.commons.exception.BizException;
import io.github.iogogogo.commons.http.OkHttpUtils;
import io.github.iogogogo.commons.util.JsonParse;
import io.github.iogogogo.commons.util.SuperBeanUtils;
import io.github.iogogogo.scheduled.model.XxlJobInfo;
import io.github.iogogogo.scheduled.properties.XxlJobProperties;
import io.github.iogogogo.scheduled.service.JobInfoService;
import io.github.iogogogo.scheduled.service.JobLoginService;
import io.github.iogogogo.scheduled.support.XxlJobHttpConfig;
import io.github.iogogogo.scheduled.support.XxlJobResponseWrapper;
import io.vavr.Tuple3;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by tao.zeng on 2024/11/20.
 */
@Slf4j
@Component
public class JobInfoServiceImpl implements JobInfoService, InitializingBean {


    @Resource
    private JobLoginService jobLoginService;

    @Resource
    private XxlJobProperties xxlJobProperties;

    private XxlJobProperties.AdminProperties admin;

    @Override
    public void afterPropertiesSet() throws Exception {
        admin = xxlJobProperties.getAdmin();
    }

    @Override
    public List<XxlJobInfo> getJobInfo(Integer jobGroupId, String executorHandler) {
        String url = String.join("/", admin.getAddresses(), "jobinfo/pageList");

        Map<String, Object> params = Maps.newHashMap();
        params.put("jobGroup", jobGroupId);
        params.put("executorHandler", StringUtils.isEmpty(executorHandler) ? "" : executorHandler);
        params.put("triggerStatus", -1);

        OkHttpUtils okHttpUtils = OkHttpUtils.getInstance().setOkHttpClient(XxlJobHttpConfig.getInstance().getOkHttpClient());
        Tuple3<Integer, Boolean, String> tuple3 = okHttpUtils.postForm(url, params, Map.of("cookie", jobLoginService.getCookie()));
        String respJson = tuple3._3;
        log.debug("xxl-job getJobInfo respJson: {}", respJson);

        XxlJobResponseWrapper<List<XxlJobInfo>> wrapper = JsonParse.tryParse(respJson, new TypeReference<>() {
        });

        return Objects.nonNull(wrapper) ? wrapper.getData() : List.of();
    }

    @Override
    public Integer addJobInfo(XxlJobInfo xxlJobInfo) {
        String url = String.join("/", admin.getAddresses(), "jobinfo/add");
        Map<String, Object> map = saveOrUpdateJob(url, xxlJobInfo);
        if (MapUtils.isNotEmpty(map) && StringUtils.equals(map.get("code").toString(), "200")) {
            log.debug("xxl-job save job succeed");
            return (Integer) map.getOrDefault("content", -1);
        } else {
            throw new BizException("xxl-job save job failure.");
        }
    }

    @Override
    public Boolean updateJobInfo(XxlJobInfo xxlJobInfo) {
        String url = String.join("/", admin.getAddresses(), "jobinfo/update");
        Map<String, Object> map = saveOrUpdateJob(url, xxlJobInfo);
        return StringUtils.equals(String.valueOf(map.getOrDefault("code", "200")), "200");
    }

    private Map<String, Object> saveOrUpdateJob(String url, XxlJobInfo xxlJobInfo) {
        OkHttpUtils okHttpUtils = OkHttpUtils.getInstance().setOkHttpClient(XxlJobHttpConfig.getInstance().getOkHttpClient());
        Tuple3<Integer, Boolean, String> tuple3 = okHttpUtils.postForm(url, SuperBeanUtils.beanToMapForSpringAPI(xxlJobInfo), Map.of("cookie", jobLoginService.getCookie()));
        String respJson = tuple3._3;
        log.debug("xxl-job saveOrUpdateJob respJson: {}", respJson);

        return JsonParse.tryParse(respJson, new TypeReference<>() {
        });
    }
}
